package com.example.wan1.view.login;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.wan1.R;
import com.example.wan1.base.activity.SimpleActivity;
import com.example.wan1.data.RetrofitUtil;
import com.example.wan1.model.CoinBean;
import com.example.wan1.model.PersonBean;
import com.example.wan1.model.UserBean;
import com.example.wan1.utils.AppUtils;
import com.example.wan1.utils.CheckDoubleClick;
import com.example.wan1.utils.SPUtils;
import com.example.wan1.utils.StatusBarUtil;
import com.example.wan1.utils.ToastUtils;
import com.example.wan1.utils.ToolsUtils;
import com.example.wan1.view.MainActivity;
import com.example.wan1.view.coin.LoginCoinContract;
import com.example.wan1.view.coin.LoginCoinPresenter;
import com.google.android.material.textfield.TextInputLayout;
import com.jakewharton.rxbinding2.widget.RxTextView;

import javax.inject.Inject;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/***
 * 1.加上刷新和加载更多
 */
public class LoginActivity extends SimpleActivity implements LoginContract.View, LoginCoinContract.View {

    @BindView(R.id.title)
    TextView mTitle;
    @BindView(R.id.search)
    ImageView mSearch;
    @BindView(R.id.login_user_et)
    EditText mLoginUserEt;
    @BindView(R.id.login_user)
    TextInputLayout mLoginUser;
    @BindView(R.id.login_pwd_et)
    EditText mLoginPwdEt;
    @BindView(R.id.login_pwd)
    TextInputLayout mLoginPwd;
    @BindView(R.id.tv_register)
    TextView mTvRegister;
    @BindView(R.id.tv_forgetpassword)
    TextView mTvForgetpassword;
    @BindView(R.id.login_btn)
    Button mLoginBtn;
    @BindView(R.id.login_tbar)
    Toolbar mToolbar;

//    @InjectPresenter
//    LoginPresenter mPresenter;
//    @InjectPresenter
//    LoginCoinPresenter mLoginCoinPresenter;

    @Inject
    LoginPresenter mPresenter;
    @Inject
    LoginCoinPresenter mLoginCoinPresenter;

    private CharSequence mResult;
    private UserBean mUserBean;


    @Override
    protected int initLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initData() {

    }

    @SuppressLint("CheckResult")
    @Override
    protected void initView() {
        mTitle.setText(getString(R.string.login));
        mSearch.setVisibility(View.GONE);
        initTbar();

        RxTextView.textChanges(mLoginUserEt).subscribe(charSequence -> {
            if (charSequence.length() > 0 && !TextUtils.isEmpty(mLoginPwdEt.getText().toString()))
                mLoginBtn.setEnabled(true);
            else
                mLoginBtn.setEnabled(false);
        });
        RxTextView.textChanges(mLoginPwdEt).subscribe(charSequence -> {
            if (charSequence.length() > 0 && !TextUtils.isEmpty(mLoginUserEt.getText().toString()))
                mLoginBtn.setEnabled(true);
            else
                mLoginBtn.setEnabled(false);
        });
        //设置主题颜色
        int color = ToolsUtils.getThemeColor(this);
        if (color != 0) {
            mToolbar.setBackgroundColor(color);
            StatusBarUtil.setColor(this, color, 0);
            mLoginBtn.setBackgroundColor(color);
            mLoginPwd.setPasswordVisibilityToggleTintList(ColorStateList.valueOf(color));
        }
    }

    private void initTbar() {
        setSupportActionBar(mToolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    public void loginSuccess(PersonBean user) {
        //保存登录的状态
        Log.i("zxd", "loginSuccess: 登陆成功");
        //这里似乎不需要保存什么，需要发送事件，告诉其它界面我登陆了，改变化的得变化
        mUserBean = new UserBean();
        mUserBean.setUsername(user.getUsername());
        mUserBean.setPassword(user.getPassword());

        mResult = TextUtils.concat(user.getUsername(), "-", user.getPassword(), "-");
        mLoginCoinPresenter.getselfCoin();
    }

    @Override
    public void loginFailure(String msg) {
        ToastUtils.showToast(msg);
    }

    @OnClick({R.id.login_btn, R.id.tv_register, R.id.tv_forgetpassword})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.login_btn:
                if (CheckDoubleClick.isFastDoubleClick()) return;
//                Log.i("zxd", "login: " + AppUtils.isLogin());
//                AppUtils.setIsLogin(true);
                RetrofitUtil.refresh();//登录成功后需要先加上cookie
                mPresenter.login(mLoginUserEt.getText().toString(), mLoginPwdEt.getText().toString());
                break;
            case R.id.tv_register:
                finish();
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.tv_forgetpassword:
                ToastUtils.showToast("接口未提供！");
                break;
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void selfCoinSuccess(CoinBean data) {
        Log.i("zxd", "selfCoinSuccess: " + data.getLevel());
        //需要去请求数据才能得到具体的排名和等级
        mUserBean.setCoinCount(data.getCoinCount());
        mUserBean.setLevel(data.getLevel());
        mUserBean.setRank(data.getRank());
//        CharSequence result = TextUtils.concat(mResult, data.getRank() + "", "-",
//                data.getCoinCount() + "", "-", data.getLevel() + "");
        //SPUtils.put(this, "user_info", result);
        //改成数据库的模式，保存用户信息，并且把登陆状态使用sp保存了一下，当然也可以通过UserManager的isLogin的方法进行判断
        UserManager.getInstance().save(mUserBean);

        //登录成功直接到首页去
        startActivity(new Intent(LoginActivity.this, MainActivity.class));
        finish();
        //RxBus.getDefault().post(new LoginEvent("登陆成功"));
    }

    @Override
    public void selfCoinFailure(String msg) {
        //do nothing
    }
}
